package edu.geo.geoutils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DBConnection implements DBConnectionProvider{
	
	static private final Log LOGGER = LogFactory.getLog(DBConnection.class);
	
	private String dbResource;
	
	
	public DBConnection(String dbName)
	{
		dbResource = dbName;
	}

	public Connection getConnection() throws SQLException{
		Connection conn = null;
		try
		{
			Context context = new InitialContext();
			DataSource ds = (DataSource) context.lookup( "java:comp/env/jdbc/" + dbResource );
			conn = ds.getConnection();			
		}
		catch (NamingException e)
		{
			LOGGER.error(e.getMessage(), e);
			throw new SQLException("Cannot open the db connection: " + e.getExplanation());
		}
		catch ( Exception e )
		{
			LOGGER.error(e.getMessage(), e);			
		}
		return conn;
	}


	public static Throwable close(Object... args)
	{
		Throwable toThrow = null;
		for (Object item : args)
		{
			if (item == null)
			{
				continue;
			}
			try
			{
				Method closeMethod = item.getClass().getMethod("close",
						(Class[]) null);
				try
				{
				    closeMethod.setAccessible( true );
					closeMethod.invoke(item, (Object[]) null);
				}
				catch (InvocationTargetException tExc)
				{
					Throwable e = tExc.getCause();
					if (toThrow != null)
					{
						e.initCause(toThrow);
						LOGGER.error(e.getMessage(), e);
					}
					toThrow = e;
				}
			}
			catch (IllegalArgumentException e)
			{
				LOGGER.error(e.getMessage(), e);
			}
			catch (IllegalAccessException e)
			{
				LOGGER.error(e.getMessage(), e);
			}
			catch (NoSuchMethodException e)
			{
				LOGGER.error(e.getMessage(), e);
				
			}
		}
		return toThrow;
	}

}
